#include "myCalCilent.hpp"

enum
{
    LEFT,
    OPER,
    RIGHT
};

void ParseLine(Request& req,const string& line)
{
    std::string left, right;
    char op;
    int status = LEFT;

    int i = 0;
    while(i < line.size())
    {
        switch (status)
        {
        case LEFT:
            if (isdigit(line[i]))
                left.push_back(line[i++]);
            else
                status = OPER;
            break;
        case OPER:
            op = line[i++];
            status = RIGHT;
            break;
        case RIGHT:
            if (isdigit(line[i]))
                right.push_back(line[i++]);
            break;
        }
    }

    req._x = std::stoi(left);
    req._y = std::stoi(right);
    req._op = op;
}

int main(int arc, char *args[])
{
    string strIP = args[1];
    uint16_t Port = toInt(args[2]);
    struct sockaddr_in peer;
    memset(&peer, 0, sizeof(peer));
    peer.sin_addr.s_addr=inet_addr(strIP.c_str());
    peer.sin_family = AF_INET;
    peer.sin_port = htons(Port);

    Sock cilSock;
    cilSock.Socket();
    int n = connect(cilSock.Fd(), (struct sockaddr *)&peer, sizeof(peer));
    
    if (n < 0)
    {
        logMessge(FATAL, "连接失败！错误码：%d ,错误原因：%s", errno, strerror(errno));
        exit(CONNECT_ERR);
    }
    logMessge(DEBUG,"准备就绪！");
    while (1)
    {
        cout << "Please Enter# ";
        string strIn;
        getline(cin,strIn);
        string temp=strIn;
        temp+=" = ";
        Request rq;
        ParseLine(rq,strIn);
        string strRq;
        rq.Serialize(&strRq);
        AddHeader(strRq);
        if (send(cilSock.Fd(), strRq.c_str(), strRq.size(), 0) < 0) // 发送给服务器
        {
            logMessge(FATAL,"服务器关闭，我也要退出了！");
            exit(SENDTO_ERR);
        }
        char respBuf[1024]={0};
        int n=recv(cilSock.Fd(),respBuf,sizeof(respBuf)-1,0);
        if(n<0)
        {
            logMessge(WARING,"接受失败，重新接受数据！ 错误码：%d ,错误原因：%s");
            continue;
        }
        Response resp;
        string strResp=respBuf;

        RemoveHeader(strResp);//去报头
        resp.DeSerialize(strResp);//反序列化
        cout<<temp<<resp._result<<" ["<<resp._code<<"] "<<endl;

    }
    close(cilSock.Fd());
    return 0;
}